package com.shuoyue.ycgk.ui.course.info;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.tabs.TabLayout;
import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.base.baseadapter.IndexFragmentAdapter;
import com.shuoyue.ycgk.entity.Course;
import com.shuoyue.ycgk.entity.CourseInfo;
import com.shuoyue.ycgk.entity.TimerTable;
import com.shuoyue.ycgk.entity.course_teacher.AppPrice;
import com.shuoyue.ycgk.entity.course_teacher.Teacher;
import com.shuoyue.ycgk.ui.common.CollectContract;
import com.shuoyue.ycgk.ui.common.CstWebActivity;
import com.shuoyue.ycgk.ui.course.adapter.TeacherAdapter;
import com.shuoyue.ycgk.ui.course.contract.CourseContract;
import com.shuoyue.ycgk.ui.course.playvideo.PlayVideoActivity;
import com.shuoyue.ycgk.ui.pay.PreCourseOrderActivity;
import com.shuoyue.ycgk.utils.HorizontalSpacesItemDecoration;
import com.shuoyue.ycgk.utils.ShareUtil;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.views.TabLayoutUtil;
import com.shuoyue.ycgk.views.dialog.common.BigHintDialog;
import com.shuoyue.ycgk.views.dialog.common.HintDialog;
import com.shuoyue.ycgk.views.dialog.pricedialog.PriceDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 课程详情
 */
public class CourseInfoActivity extends BaseMvpActivity<CourseContract.Presenter>
        implements CourseContract.CourseListView {

    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.time_count)
    TextView timeCount;
    @BindView(R.id.learn_count)
    TextView learnCount;
    @BindView(R.id.lay_top)
    LinearLayout layTop;
    @BindView(R.id.line_spe)
    View lineSpe;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.buy)
    Button buy;
    @BindView(R.id.teachersRecycleView)
    RecyclerView teachersRecycleView;
    @BindView(R.id.lay_bottom)
    LinearLayout layBottom;
    @BindView(R.id.free)
    TextView free;
    @BindView(R.id.price_org)
    TextView priceOrg;
    @BindView(R.id.vip_price)
    TextView vipPrice;
    @BindView(R.id.lay_price)
    LinearLayout layPrice;
    @BindView(R.id.free2)
    TextView free2;
    @BindView(R.id.price2)
    TextView price2;
    @BindView(R.id.price_org2)
    TextView priceOrg2;
    @BindView(R.id.vip_price2)
    TextView vipPrice2;
    @BindView(R.id.lay_price2)
    LinearLayout layPrice2;
    @BindView(R.id.lay_price_org)
    FrameLayout layPriceOrg;
    @BindView(R.id.lay_price_vip)
    LinearLayout layPriceVip;
    @BindView(R.id.lay_price_org2)
    FrameLayout layPriceOrg2;
    @BindView(R.id.lay_price_vip2)
    LinearLayout layPriceVip2;
    //    @BindView(R.id.collection)
//    ImageView collection;
    @BindView(R.id.effectTime)
    TextView effectTime;
    @BindView(R.id.activity_price)
    TextView activityPrice;
    @BindView(R.id.lay_price_activity)
    LinearLayout lay_priceActivity;
    //设置手势识别监听器;转换方式
    boolean isAtTop = false;
    CourseInfo course;
    List<BaseMvpFragment> fragmentList = new ArrayList<>();
    TeacherAdapter teacherAdapter;
    IndexFragmentAdapter indexFragmentAdapter;

//    CollectContract.Presenter collectPresenter;


    FragmentCourseTimetable fragmentCourseTimetable;

    int id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_course_info_aps;
    }

    @Override
    protected void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        teachersRecycleView.setLayoutManager(linearLayoutManager);
        teachersRecycleView.addItemDecoration(new HorizontalSpacesItemDecoration(SizeUtil.dip2px(mContext, 8), false));
        teacherAdapter = new TeacherAdapter(null);
        teachersRecycleView.setAdapter(teacherAdapter);
        teacherAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Teacher t = (Teacher) adapter.getItem(position);
            BigHintDialog hintDialog = new BigHintDialog(mContext, t.getTeacher().getUser().getFullName(), t.getTeacher().getUser().getProfile());
            hintDialog.show();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getCourseInfo(id);
    }

    void setCourseData(CourseInfo course) {
        title.setText(course.getProduct().getName());
//        collection.setImageResource(course.getIsCollect() == 1 ? R.mipmap.collection_y : R.mipmap.collection_n);

        Glide.with(mContext).load(course.getProduct().getCover()).error(R.mipmap.img_loading_gray).into(img);
        timeCount.setText("共" + course.getProduct().getAmount() + "课时");
        learnCount.setText("已有" + course.getProduct().getSalesVolume() + "人学习");
        if (viewPager.getChildCount() == 0) {
            indexFragmentAdapter = new IndexFragmentAdapter(getSupportFragmentManager(), fragmentList);
            fragmentList.add(FragmentCourseInfo.newInstance(course.getProduct().getIntroduce()));
            fragmentCourseTimetable = FragmentCourseTimetable.newInstance(course.getCourseArrangementList(),
                    course.getProduct(), course.getIsPay());

            fragmentList.add(fragmentCourseTimetable);
            if (course.getCourseDatas() != null && course.getCourseDatas().size() > 0) {
                fragmentList.add(FragmentCourseTeacher.newInstance(course.getTeacherList()));
            }
            tabLayout.setupWithViewPager(viewPager);
            viewPager.setOffscreenPageLimit(1);
            viewPager.setAdapter(indexFragmentAdapter);
            viewPager.setCurrentItem(0);
        }

        teacherAdapter.resetData(course.getTeacherList());

        if (course.getProduct().getIsFree() == 1 || course.getProduct().getDefaultPrice() == null) {
            free.setVisibility(View.VISIBLE);
            layPrice.setVisibility(View.GONE);
            free2.setVisibility(View.VISIBLE);
            layPrice2.setVisibility(View.GONE);
//            layBottom.setVisibility(View.GONE);
        } else {
            AppPrice appPrice = course.getProduct().getDefaultPrice();
            effectTime.setText("有效期: " + appPrice.getEffectiveTime() + "天");
//            layPriceOrg.setVisibility(appPrice.getPrice() == appPrice.getOriginalPrice() ? View.GONE : View.VISIBLE);
//            layPriceOrg2.setVisibility(appPrice.getPrice() == appPrice.getOriginalPrice() ? View.GONE : View.VISIBLE);
//            layPriceVip.setVisibility(appPrice.getPrice() == appPrice.getVipPrice() ? View.GONE : View.VISIBLE);
//            layPriceVip2.setVisibility(appPrice.getPrice() == appPrice.getVipPrice() ? View.GONE : View.VISIBLE);
            layPriceOrg.setVisibility(TextUtils.isEmpty(appPrice.getOriginalPrice())
                    ? View.GONE : View.VISIBLE);
            layPriceOrg2.setVisibility(TextUtils.isEmpty(appPrice.getOriginalPrice())
                    ? View.GONE : View.VISIBLE);
            layPriceVip.setVisibility(TextUtils.isEmpty(appPrice.getVipPrice())
                    ? View.GONE : View.VISIBLE);
            layPriceVip2.setVisibility(TextUtils.isEmpty(appPrice.getVipPrice())
                    ? View.GONE : View.VISIBLE);
            lay_priceActivity.setVisibility(TextUtils.isEmpty(appPrice.getActivityPrice())
                    ? View.GONE : View.VISIBLE);
            price.setText("￥" + appPrice.getPrice());
            price2.setText("￥" + appPrice.getPrice());
            priceOrg.setText("￥" + appPrice.getOriginalPrice());
            priceOrg2.setText("￥" + appPrice.getOriginalPrice());
            vipPrice.setText("￥" + appPrice.getVipPrice());
            vipPrice2.setText("￥" + appPrice.getVipPrice());
            activityPrice.setText("￥" + appPrice.getActivityPrice());


        }
        if (course.getIsPay() == 1
                || course.getProduct().getIsFree() == 1) {
            buy.setText("开始学习");
        } else {
            buy.setText("马上购买");
        }
    }

    @OnClick({R.id.back})
    public void onViewClicked() {
        finish();
    }

    @OnClick({R.id.buy, R.id.share, R.id.service, R.id.act_info})
    public void onViewClicked(View view) {
        if (course == null) {
            return;
        }
        switch (view.getId()) {

            case R.id.service:
//                CstWebActivity.start(mContext, Constant.serviceUrl, "咨询");
//                Uri uri = Uri.parse(Constant.serviceUrl);
//                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                startActivity(intent);
                if (Constant.isOpenServiceExploer) {
                    Uri uri = Uri.parse(Constant.serviceUrl);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                } else {
                    CstWebActivity.start(mContext, Constant.serviceUrl, "咨询");

                }

                break;
            case R.id.share:
                if (course != null)
                    ShareUtil.shareUrl(this, ShareUtil.COURSE_URL + id,
                            course.getProduct().getName(),
                            course.getProduct().getBrief(),
                            null);

                break;
            case R.id.buy:
                if (course.getIsPay() == 1 || course.getProduct().getIsFree() == 1) {
                    //进入学习
                    if (course.getProduct().getIsApp() != 1) {
                        toast("该课程不能在APP上播放");
                        return;
                    }
                    startActivityForResult(new Intent(mContext, PlayVideoActivity.class)
                            .putExtra("table", course.getCourseArrangementList())
                            .putExtra("play", course.getCourseArrangeId())
                            .putExtra("isPay", 1)
                            .putExtra("course", course.getProduct()), 1002);
                } else {
                    if (course.getProduct().getProductPriceList() == null) {
                        PreCourseOrderActivity.start(mContext, course.getProduct(),
                                course.getProduct().getDefaultPrice().getPrice(),
                                course.getProduct().getDefaultPrice().getId(), course.getProduct().getSubjectTypeId());
                    } else {
                        PriceDialog priceDialog = new PriceDialog(mContext, course.getProduct().getProductPriceList());
                        priceDialog.addSelectCall(speed -> {
                            PreCourseOrderActivity.start(mContext, course.getProduct(), speed.getPrice(), speed.getId(), course.getProduct().getSubjectTypeId());
                        });
                        priceDialog.show();
                    }
                }
                break;
            case R.id.act_info:
                if (!TextUtils.isEmpty(course.getProduct().getDefaultPrice().getRemark())) {
                    HintDialog hintDialog = new HintDialog(mContext, "活动详情", course.getProduct().getDefaultPrice().getRemark());
                    hintDialog.show();
                }


                break;
//            case R.id.collection:
//                if (course.getIsCollect() == 1) {
//                    collectPresenter.deleteCollection(course.getProduct().getId(), 4);
//                } else {
//                    collectPresenter.saveCollect(course.getProduct().getId(), 4);
//                }
//                collection.setEnabled(false);
//                break;
        }
    }


    @Override
    public void initData() {
        id = getIntent().getIntExtra("id", -1);
//        collectPresenter = new CollectContract.Presenter();
//        collectPresenter.attachView(this);
        mPresenter = new CourseContract.Presenter();
        mPresenter.attachView(this);
//        mPresenter.getCourseInfo(id);
    }


    @Override
    public void setCourseList(ListWithPage<Course> list) {

    }

    @Override
    public void setCourseInfo(CourseInfo info) {
        this.course = info;
        setCourseData(course);
    }

    @Override
    public void setVideoInfo(TimerTable timerTable, TimerTable adapterData) {

    }

    @Override
    public void notBuyNotice() {

    }

//
//    @Override
//    public void addCollectSuc() {
//        collection.setImageResource(R.mipmap.collection_y);
//        collection.setEnabled(true);
//        course.setIsCollect(1);
//
//    }
//
//    @Override
//    public void deleteCollectSuc() {
//        collection.setImageResource(R.mipmap.collection_n);
//        collection.setEnabled(true);
//        course.setIsCollect(0);
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            ArrayList<TimerTable> tables = (ArrayList<TimerTable>) data.getSerializableExtra("table");
            int index = data.getIntExtra("index", -1);
            if (index != -1)
                course.setCourseArrangeId(index);
            if (tables != null && fragmentCourseTimetable != null) {
                fragmentCourseTimetable.resetTimeTable(tables);
            }
        }
    }


}
